<?php
class User_Model_Accounts extends Zend_Db_Table_Abstract 

{
	
	/**
	 * Model Account
	 * 
	 * @author Nguyen Manh Hung
	 */
	protected $_name = TABLE_USERS;
	protected $_id = 'id';
	
	/**
	 * function insert new members to database
	 * 
	 * @author Nguyen Manh Hung
	 */
	public function createUser($first_name, $last_name, $username, $password, $email, $gender = 1, $active = 1, $group = 2, $address = '', $dob = '', $avatarurl = '', $info = '', $emailshow = 0, $receiveadminemails = 0) 

	{
		$dateCreated = new Zend_Db_Expr ( 'NOW()' );
		
		$row = $this->createRow ();
		
		$row->first_name = $first_name;
		
		$row->last_name = $last_name;
		
		$row->username = $username;
		
		$row->password = $password;
		
		$row->email = $email;
		
		$row->emailshow = $emailshow;
		
		$row->receiveadminemails = $receiveadminemails;
		
		if ($avatarurl) {
			$row->avatarurl = $avatarurl;
		} else {
			
			$row->avatarurl = "images/no_avatar.jpg";
		}
		
		$row->info = $info;
		
		$row->gender = $gender;
		
		if ($dob != '') {
			
			$row->dob = $dob;
		}
		
		$row->address = $address;
		
		$row->active = $active;
		
		$row->group = $group;
		
		$row->date_created = $dateCreated;
		
		$row->last_login = $dateCreated;
		
		$row->save ();
		
		$id = $row->id;
		
		return $id;
	}
	
	/**
	 * Fetch user
	 * 
	 * @author Nguyen Manh Hung
	 */
	public function fetchUser($filters = array(), $sortFeild = null, $limit = null, $page = 1) {
		$select = $this->select ();
		// add cac filter vao truy van tim kiem
		if (count ( $filters ) > 0) 

		{
			
			foreach ( $filters as $feild => $filter ) {
				
				$select->where ( $feild . ' =?', $filter );
			}
		}
		
		// add sort vao truy van
		
		if (null != $sortFeild) 

		{
			
			$select->order ( $sortFeild );
		}
		
		// add limit - offset vao truy van
		
		if (null != $limit) 

		{
			
			$offset = $page * NUM_PER_PAGE;
			
			if ($offset <= $limit) 

			{
				
				$offset = $limit + NUM_PER_PAGE;
			}
			
			$select->limit ( $limit, $offset );
		}
		
		return $this->fetchAll ( $select );
	}
	
	
	
	
	public function updateLastLogin($id) {
		$row = $this->find ( $id )->current ();
		
		if ($row) 

		{
			
			$timeLogin = new Zend_Db_Expr ( 'NOW()' );
			
			$row->last_login = $timeLogin;
			
			$row->save ();
			
			return 1;
		} else {
			
			return 0;
		}
	}
	
	/**
	 * update password
	 *
	 * @author Nguyen Manh Hung
	 *
	 */
	public function changePass($id, $password) 

	{
		
		// tim kiem user
		$rowUser = $this->find ( $id )->current ();
		
		if ($rowUser) 

		{
			
			// update pass
			
			$rowUser->password = $password;
			
			$rowUser->save ();
			
			return 1;
		} else {
			
			return 0;
		}
	}
}